package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TradeProvinceOrderWindow;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.function.DimAsyncFunction;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2022/6/1 9:13
 */
public class Dws_10_DwsTradeProvinceOrderWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_10_DwsTradeProvinceOrderWindow().init(
            3010,
            2,
            "Dws_10_DwsTradeProvinceOrderWindow",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        
        // 1. 按照 order_detail_id 去重
        SingleOutputStreamOperator<JSONObject> distinctedStream = distinctByOrderDetailId(stream);
        // 2. 解析成javaBean
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanStream = parseToBean(distinctedStream);
        // 3. 分组开窗聚合
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanStreamWithoutDim = windowAndAggregate(beanStream);
        // 4. 补充省份的维度信息
        SingleOutputStreamOperator<TradeProvinceOrderWindow> resultStream = joinDim(beanStreamWithoutDim);
        // 5. 写出到clickhouse中
        writeToClickhouse(resultStream);
        
    }
    
    private void writeToClickhouse(SingleOutputStreamOperator<TradeProvinceOrderWindow> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink(Constant.CLICKHOUSE_DB, "dws_trade_province_order_window", TradeProvinceOrderWindow.class));
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> joinDim(SingleOutputStreamOperator<TradeProvinceOrderWindow> stream) {
       return AsyncDataStream.unorderedWait(
            stream,
            new DimAsyncFunction<TradeProvinceOrderWindow>(){
    
                @Override
                public void addDim(TradeProvinceOrderWindow input, JSONObject dim) {
                    input.setProvinceName(dim.getString("NAME"));
                }
    
                @Override
                public String getTableName() {
                    return "dim_base_province";
                }
    
                @Override
                public String getDimId(TradeProvinceOrderWindow input) {
                    return input.getProvinceId();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> windowAndAggregate(
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeProvinceOrderWindow>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .keyBy(TradeProvinceOrderWindow::getProvinceId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeProvinceOrderWindow>() {
                    @Override
                    public TradeProvinceOrderWindow reduce(TradeProvinceOrderWindow b1,
                                                           TradeProvinceOrderWindow b2) throws Exception {
                        b1.setOrderAmount(b1.getOrderAmount() + b2.getOrderAmount());
                        b1.getOrderIdSet().addAll(b2.getOrderIdSet());
                        return b1;
                    }
                },
                new ProcessWindowFunction<TradeProvinceOrderWindow, TradeProvinceOrderWindow, String, TimeWindow>() {
                    
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TradeProvinceOrderWindow> elements,
                                        Collector<TradeProvinceOrderWindow> out) throws Exception {
                        
                        TradeProvinceOrderWindow bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));
                        
                        bean.setOrderCount((long) bean.getOrderIdSet().size());
                        
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> parseToBean(
        SingleOutputStreamOperator<JSONObject> distinctedStream) {
        return distinctedStream
            .map(obj ->
                     TradeProvinceOrderWindow.builder()
                         .provinceId(obj.getString("province_id"))
                         .orderIdSet(new HashSet<>(Collections.singleton(obj.getString("order_id"))))
                         .orderAmount(obj.getDoubleValue("split_total_amount"))
                         .ts(obj.getLong("ts") * 1000)
                         .build()
            );
        
    }
    
    
    private SingleOutputStreamOperator<JSONObject> distinctByOrderDetailId(DataStreamSource<String> stream) {
        /*
        去重的优化:
            没有用到右边的数据, 所以只要第一条就可以了
            
         
         */
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getString("id"))
            .process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
                
                private ValueState<JSONObject> lastOrderDetailState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 状态中存储数据, 每新来一条数据,就比较时间, 新来的大于状态中的,更新状态中的数据
                    lastOrderDetailState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("lastOrderDetailState", JSONObject.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject lastOrderDetail = lastOrderDetailState.value();
                    if (lastOrderDetail == null) {
                        lastOrderDetailState.update(obj);
                        out.collect(obj);
                    }
                }
            });
        
        
    }
    
}